<?php
namespace app\admin\controller;
use think\Db;
use think\Session;
use think\Request;
use think\Controller;

class Section extends Controller
{
	/**
	 * 加载版块管理页面
	 * @return [type] [description]
	 */
	public function index()
	{
		$name = Db::name('admin')->field('name')->where('name = "'.Session::get('admin').'"')->find();

		$list = Db::name('section')->select();
		// var_dump($list);die;
    	return $this->fetch('list',['title'=>'蒸汽男孩后台','nick'=>$name['name'],'list'=>$list]);
	}

	/**
	 * 加载版块增加页面
	 */
	public function add()
	{
		$name = Db::name('admin')->field('name')->where('name = "'.Session::get('admin').'"')->find();
		return $this->fetch('add',['title'=>'蒸汽男孩后台','nick'=>$name['name']]);
	}

	/**
	 * 执行版块增加逻辑
	 * @param  Request $req [description]
	 * @return [type]       [description]
	 */
	public function insert(Request $req)
	{
		$sql = $req->post();
		if($sql['name'] == '') {
			$this->error('请填写表单');
		}

		$sql['ctime'] = date('Y-m-d H:i:s',time());
		$data = Db::name('section')->insert(['name'=>$sql['name'],'ctime'=>$sql['ctime']]);
		if($data > 0) {
			$this->success('增加成功',url('admin/section/index'));
		} else {
			$this->error('增加失败');
		}
	}

	/**
	 * 加载版块修改页面
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function edit($id)
	{
		$name = Db::name('admin')->field('name')->where('name = "'.Session::get('admin').'"')->find();

		$data = Db::name('section')->find(['id'=>$id]);
		return $this->fetch('edit',['title'=>'蒸汽男孩后台','data'=>$data,'nick'=>$name['name']]);
	}

	/**
	 * 执行版块修改逻辑
	 * @param  Request $req [description]
	 * @param  [type]  $id  [description]
	 * @return [type]       [description]
	 */
	public function update(Request $req,$id)
	{
		$sql = $req->post();

		$data = Db::name('section')->where(['id'=>$id])->update(['name'=>$sql['name']]);

		if($data > 0) {
			$this->success('修改成功',url('admin/section/index'));
		} else {
			$this->error('修改失败');
		}
	}

	/**
	 * 执行删除版块逻辑
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function delete($id)
	{
		$data = Db::table('ubisoft_section s,ubisoft_area a')->field('a.name')->where('s.id = "'.$id.'" and s.id = a.sec_id')->select();
		// var_dump($data);die;
		if(!empty($data)) {
			$this->error('请先清空该版块下的专区');
		}
		$del = Db::name('section')->delete(['id'=>$id]);

		if($del > 0) {
			$this->success('删除成功',url('admin/section/index'));
		} else {
			$this->error('删除失败');
		}
	}
}